﻿using Blm.Utils.Extensions;
using System;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Extension;
using VisionCloud.Domain.Repository.Interface.Sys;

namespace VisionCloud.Domain.Repository.Implement.Sys
{
    public class SysMenuFuncRepository : BaseRepository<SysMenuFunc>, ISysMenuFuncRepository
    {
        public async Task<SysMenuFuncDto> FindSysMenuFunc(SysMenuFuncDto sysMenuFuncDto)
        {
            var result = Db.SysMenuFuncs.Where(p => p.Name == sysMenuFuncDto.Name)
                    .Select(w => new SysMenuFuncDto()
                    {
                        MenuFuncId = w.MenuFuncId,
                        MenuId = w.MenuId,
                        AppId = w.AppId,
                        Name = w.Name,
                        Description = w.Description,
                        Component = w.Component,
                        Icon = w.Icon,
                        Apis = w.Apis,
                        Status = w.Status
                    }).SingleOrDefault();

            return result;
        }

        public async Task<ApiPageResult> GetPage(SysMenuFuncCondition condition)
        {
            var list = await (from mf in Db.SysMenuFuncs
                              join rp in Db.SysRolePermissions on mf.MenuFuncId equals rp.MenuFuncId into t
                              from rp in t.DefaultIfEmpty()
                              where condition.Name == null || mf.Name.Contains(condition.Name, StringComparison.OrdinalIgnoreCase)
                              where condition.MenuId == Guid.Empty || mf.MenuId == condition.MenuId
                              where condition.RoleList == null || condition.RoleList.Contains(rp.RoleId)
                              select mf.CopyTo<SysMenuFuncDto>()).ToPageList(condition).ConfigureAwait(false);

            var result = condition.CopyTo<ApiPageResult>();
            result.PageData = list;
            return result;
        }
    }
}